<?php
/**
 * 用户组管理控制器
 * User: lvshuyun
 * Date: 2015/6/8
 * Time: 17:26
 */

namespace backend\controllers;


use backend\commands\BaseAdminController;
use common\models\DAO\Admin;
use common\models\DAO\AdminPower;
use common\models\DAO\AdminRole;
use yii\data\ActiveDataProvider;

class AdminRoleController extends BaseAdminController {

    /*
     * 主页兼列表页
     */
    public function actionList(){
        $AdminRole = new AdminRole();
        $dataProvider = new ActiveDataProvider([
            'query' => $AdminRole->find(),
            'pagination' => [
                'pageSize' => 20,
            ]
        ]);
        return $this->render('list', ['model'=>$AdminRole, 'dataProvider'=>$dataProvider]);
    }

    /*
     * 添加管理员组以及权限
     */
    public function actionAdd(){
        $AdminRole = new AdminRole(['scenario' => 'add']);
        $request = \Yii::$app->request;
        if($request->isPost){
            if ($AdminRole->load($request->post())) {
                if($AdminRole->save()){
                    //保存权限
                    $this->savePowers($AdminRole->id, $request->post('power'));
                    return $this->renderMessage('添加成功!', 'admin-role/list', 'success');
                }
            }
            return $this->renderMessage('添加失败!', -1, 'danger');
        }else{
            return $this->render('add', ['adminRole'=>$AdminRole, 'allPowers'=>$this->getAllPowers()]);
        }
    }

    /**
     * 角色权限编辑
     */
    public function actionEdit($id)
    {
        if($id > 1){
            $model = AdminRole::findOne($id);
            if(!empty($model)){
                $request = \Yii::$app->request;
                if($request->isPost){
                    $model->setScenario('edit');
                    if ($model->load($request->post())) {
                        if($model->save()){
                            $powers = $request->post('power');
                            if(!empty($powers)){
                                //保存权限
                                $this->savePowers($id, $powers);
                            }
                            return $this->renderMessage('保存成功!', 'admin-role/list', 'success');
                        }
                    }
                    return $this->renderMessage('保存失败!', -1, 'danger', $model->getFirstErrors());
                }else{
                    $powers = (new AdminPower())->getByRole($id);
                    $simple_powers = array();
                    foreach($powers as $p){
                        $simple_powers[] = $p['controller'] .'/'. $p['action'];
                    }
                    return $this->render('edit', [
                        'model' => $model,
                        'powers' => $simple_powers,
                        'allPowers' => $this->getAllPowers()
                    ]);
                }
            }else{
                return $this->renderMessage('ID错误', '-1', 'danger');
            }
        }else{
            return $this->renderMessage('超级管理员禁止修改', '-1', 'danger');
        }

    }

    /**
     * 删除管理员组
     */
    public function actionDelete($id){
        $AdminRole = (new AdminRole())->findOne(intval($id));
        if($AdminRole){
            if((new Admin())->find()->where(['roleID'=>$id])->count()){
                return $this->renderMessage('该管理员组下还有管理员，请先删除或移动相应的管理员后再删除管理员组', 'admin-role/index', 'danger');
            }
            if($AdminRole->delete()){
                (new AdminPower())->delRolePower($id);
            }
            return $this->renderMessage('删除成功', '-1', 'success');

        }else{
            return $this->renderMessage('ID错误', '-1', 'danger');
        }
    }

    /**
     * ActiveForm的Ajax验证验证
     */
    public function actionAjaxValidate(){
        return $this->ajaxValidate(new AdminRole());
    }

    /*
     * 获得所有权限
     */
    private function getAllPowers(){
        return \Yii::$app->params['admin_menu'];
    }

    /**
     * 保存权限
     * 不管添加管理员组还是修改管理员组，都可以调用这个
     * @param int $id 角色ID
     * @param array $powers Post的Power数组
     */
    private function savePowers($id, $powers){
        if(!empty($powers) && is_array($powers)){
            $data = array();
            foreach($powers as $p){
                $a = explode('/', $p);

                $data[] = array(
                    'controller' => $a[0],
                    'action' => $a[1],
                );
            }
            return  (new AdminPower())->updatePowers($id, $data);
        }
        return false;
    }


}